<template lang="pug">
.list
  .material-section
    .material-section-title 分享显示标题：
    .material-section-list
      el-input(placeholder="请输入标题" v-model="title" size="small" style="width: 400px;")
      .el-input-info 请输入5~30个字符
    .material-section-right
  .material-section
    .material-section-title 分享海报图：
    .material-section-list
      .material-section-bd
        .el-image-info 建议上传286*433的图片，最多上传5张
        .material-image-bd
          .material-image-item
            el-upload(
              action="#"
              :multiple="false"
              accept="image/png, image/jpeg, image/jpg, image/gif"
              ref="materialImgUpload"
              list-type="picture"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="(file, fileList) => {handleChange(file, fileList, -1)}"
              :on-exceed="handleExceed"
              style="display: inline-block;"
            )
              .el-upload-btn(slot="trigger")
                .iconfont.icon-tianjia
                .el-upload-btn-txt 点击上传
            .el-progress-bd(v-if="progressFlag")
              el-progress(:text-inside="true" :stroke-width="16" :percentage="loadProgress")
          .material-image-item(v-for="(item, index) in fileList" :key="index")
            .material-image-relative
              el-upload(
                action="#"
                :multiple="false"
                accept="image/png, image/jpeg, image/jpg, image/gif"
                :ref="'materialImgUpload'+index"
                list-type="picture"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="(file, fileList) => {handleChange(file, fileList, index)}"
                :on-exceed="handleExceed"
                style="display: inline-block;"
              )
                .el-replace-btn(slot="trigger") 更换图片
              i(class="el-icon-circle-close" @click.stop="delFile(index)")
              img(:src="item.fileUrl" style="width:148px; height:148px")
            .el-progress-bd(v-if="item.progressFlag")
              el-progress(:text-inside="true" :stroke-width="16" :percentage="item.loadProgress")
    .material-section-right
  .material-section
    .material-section-title
    .material-section-list
      el-button(@click="save" type="primary" size="small") 保存
    .material-section-right
</template>

<script>
import { getShareConfig, FileUpload, getStsInformation, setShareConfig } from 'api'
export default {
  name: 'shareManage',
  data () {
    return {
      title: '',
      fileList: [],
      file: '',
      hostName: '',
      progressFlag: false,
      loadProgress: 0
    }
  },
  methods: {
    async getShareConfigList () {
      try {
        const { ResultSet } = await this.$axios.post(getShareConfig)
        this.title = ResultSet.userData.title || ''
        this.fileList = (ResultSet.userData.shareList || []).map(item => {
          return {
            fileId: item.fileId,
            fileUrl: item.fileUrl,
            progressFlag: false,
            loadProgress: 0
          }
        })
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getStsInformation () {
      try {
        const { ResultSet } = await this.$axios.post(getStsInformation)
        this.hostName = ResultSet.userData.hostName || ''
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async fileUpload (raw, index) {
      return new Promise(async (resolve, reject) => {
        try {
          if(index > -1) {
            this.fileList[index].progressFlag = true //显示进度条
            this.fileList[index].loadProgress = 0
          } else {
            this.progressFlag = true //显示进度条
            this.loadProgress = 0
          }
          let formData = new FormData()
          formData.append('Filedata', raw)
          formData.append("applicationId", 4)
          const { ResultSet } = await this.$axios.post(FileUpload, { formData: formData, isUpload: true }, { headers:{ "Content-Type": "multipart/form-data" }, onUploadProgress: progress => {
            if(progress.lengthComputable) {
              if(index > -1) {
                this.fileList[index].loadProgress = (progress.loaded / progress.total).toFixed(2) * 100 //进度条百分比
              } else {
                this.loadProgress = (progress.loaded / progress.total).toFixed(2) * 100 //进度条百分比
              }
            }
          }})
          resolve({ ...ResultSet.Result[0] })
        } catch (err) {
          console.log(err)
          reject(err)
        }
      })
    },
    init () {
      this.getShareConfigList()
      this.getStsInformation()
    },
    async uploadFile (index) {
      try {
        const imgFile = await this.fileUpload(this.file.raw, index)
        let fileId = imgFile.fileId
        let fileUrl = imgFile.fileUrl
        if(index > -1) {
          this.fileList.splice(index, 1, {
            fileId: fileId,
            fileUrl: this.hostName + '/' + fileUrl,
            progressFlag: false,
            loadProgress: 0
          })
        } else {
          this.fileList.unshift({
            fileId: fileId,
            fileUrl: this.hostName + '/' + fileUrl,
            progressFlag: false,
            loadProgress: 0
          })
          this.progressFlag = false
          this.loadProgress = 0
        }
        this.file = ''

        this.$message.success('上传成功！')
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    handleExceed () {
      this.$message.error('最多只能上传1张图片！')
    },
    delFile (index) {
      this.fileList.splice(index, 1)
    },
    handleChange (file, fileList, index) {
      if (this.fileList && index === -1 && this.fileList.length >= 5) {
        this.$message.error('最多上传5张图片！')
        return
      }
      if(index > -1) {
        this.$refs[`materialImgUpload${index}`][0].clearFiles()
      } else {
        this.$refs.materialImgUpload.clearFiles()
      }
      this.file = file
      this.uploadFile(index)
    },
    async save () {
      if (!this.title) {
        this.$message.error('请填写标题！')
        return
      }
      if (!this.fileList || this.fileList.length == 0) {
        this.$message.error('请上传分享海报图！')
        return
      }
      if (this.title.length < 5 || this.title.length > 30) {
        this.$message.error('分享显示标题请输入5~30个字符！')
        return
      }
      if (this.fileList.length > 5) {
        this.$message.error('最多上传5张分享海报图！')
        return
      }
      try {
        if (this.lock) return
        this.lock = true
        let query = {
          title: this.title,
          fileIds: this.fileList.map(item => item.fileId)
        }
        await this.$axios.post(setShareConfig, { ...query })
        this.lock = false
        this.$message.success('保存成功！')
        this.getShareConfigList()
      } catch (err) {
        this.lock = false
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }

    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.init()
    })
  }
}
</script>

<style lang="scss" scoped>
.list {
  width: 100%;
  min-height: 100%;
  background: #FFFFFF;
  border: 1px solid #F3F3F4;
  box-sizing: border-box;
  box-shadow: 0px 4px 0px #F3F3F4;
  border-radius: 10px;
  padding: 0 40px;
}
.material-section {
  padding: 16px 0;
  display: flex;
}
.material-section-title {
  flex: 2;
  font-size: 16px;
  line-height: 24px;
  color: #3E4373;
  margin-right: 16px;
}
.material-section-list {
  flex: 11;
  display: flex;
  flex-wrap: wrap;
}
.material-section-right {
  flex: 11;
}

.el-input-info {
  margin-left: 10px;
  font-size: 14px;
  line-height: 32px;
  color: #AFAFAF;
}
.el-image-info {
  font-size: 14px;
  line-height: 24px;
  color: #AFAFAF;
  margin-bottom: 24px;
}
.material-image-bd {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}
.material-image-item {
  padding-right: 24px;
  padding-bottom: 24px;
  .material-image-relative {
    position: relative;
  }
}

.el-progress-bd {
  padding: 5px 0;
}
.el-upload-btn {
  width: 148px;
  height: 148px;
  background: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: #B2B4C7;
  border: 1px dashed #c0ccda;
  &:hover {
    border-color: #FF708B;
    color: #FF708B;
  }
  .iconfont {
    font-size: 20px;
    font-weight: bold;
  }
  .el-upload-btn-txt {
    font-size: 14px;
  }
}
.el-icon-circle-close {
  position: absolute;
  top: -10px;
  right: -10px;
  z-index: 1;
  font-size: 20px;
  color: #EE0A24;
  cursor: pointer;
}
.el-replace-btn {
  width: 148px;
  height: 28px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 14px;
  line-height: 28px;
  text-align: center;
  cursor: pointer;
  position: absolute;
  bottom: 0;
  z-index: 1;
}
</style>
